package projects

import (
	"encoding/json"
	"github.com/beego/beego/v2/core/validation"
	"log"
	"strconv"
	"strings"
	"xpms/controllers"
	"xpms/cores/utils"
)

// 需求管理
type NeedsSwimlaneProjectController struct {
	controllers.BaseController
}

// @Title 更新泳道
// @Description   更新泳道
// @Param	body		body 	projects.SwimlaneDto	true		"body for Swimlane content"
// @Success 200 {string} 更新泳道成功
// @Failure 403 body is empty
// @router /:id [put]
func (u *NeedsSwimlaneProjectController) UpdateSwimlane() {
	id, err := u.GetInt64(":id")
	if err != nil || id < 0 {
		// handle error
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "未知泳道"}
		u.ServeJSON()
		return
	}
	var dto SwimlaneDto
	err = json.Unmarshal(u.Ctx.Input.RequestBody, &dto)
	if err != nil {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "解析json错误" + err.Error()}
		u.ServeJSON()
		return
	}
	//雪花算法ID生成
	needs := new(NeedsSwimlanes)
	utils.SimpleCopyProperties(needs, dto)
	err = UpdateNeedsSwimlanes(id, *needs)
	if err == nil {
		u.Data["json"] = map[string]interface{}{"code": 1, "message": "信息修改成功"}
	} else {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "信息修改失败:" + err.Error()}
	}
	u.ServeJSON()
}

// @Title Delete
// @Description get swimlane  by id
// @Param	id		path 	string	true		"The key for swimlane"
// @Success 200 {string} 删除成功
// @Failure 403 :id is empty
// @router /:id [delete]
func (u *NeedsSwimlaneProjectController) DeleteSwimlane() {
	uid := u.GetString(":id")
	if uid != "" {
		int64, err := strconv.ParseInt(uid, 10, 64)
		if err != nil {
			u.Data["json"] = map[string]interface{}{"code": 0, "message": "信息删除失败:" + err.Error()}
			return
		}
		err = IfsDeleteSwimlane(int64)
		if err != nil {
			u.Data["json"] = map[string]interface{}{"code": 0, "message": "信息删除失败:" + err.Error()}
			return
		}

		err = DeleteSwimlane(int64)
		if err == nil {
			u.Data["json"] = map[string]interface{}{"code": 1, "message": "信息删除成功"}
		} else {
			u.Data["json"] = map[string]interface{}{"code": 0, "message": "信息删除失败:" + err.Error()}
		}
	}
	u.ServeJSON()
}

// @Title 泳道
// @Description 泳道
// @Param	id		path 	string	true		"项目id"
// @Success 200 {object} projects.NeedsSwimlanes   int   int  int
// @Failure 403 泳道 not exist
// @router /:id/list [get]
func (u *NeedsSwimlaneProjectController) List() {
	id, err := u.GetInt64(":id")
	if err != nil || id < 0 {
		// handle error
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "未知项目" + err.Error()}
		u.ServeJSON()
		return
	}
	u.Data["json"] = GetNeedsSwimlanesByProjectId(id)
	u.ServeJSON()
}

type SwimlaneDto struct {
	Projectid   int64 `json:"Projectid,string"`
	Name        string
	Type        int
	Status      int
	Xcoordinate float64
	Ycoordinate float64
	Colour      string
	Orders      int
	High        int
	Width       int
}

// @Title 创建泳道
// @Description   创建泳道
// @Param	body		body 	projects.SwimlaneDto	true		"body for Swimlane content"
// @Success 200 {string} 创建泳道成功
// @Failure 403 body is empty
// @router / [post]
func (u *NeedsSwimlaneProjectController) CreateSwimlane() {
	var dto SwimlaneDto
	err := json.Unmarshal(u.Ctx.Input.RequestBody, &dto)
	if err != nil {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "解析json错误" + err.Error()}
		u.ServeJSON()
		return
	}
	// 开始校验输入值
	valid := validation.Validation{}
	valid.Required(dto.Projectid, "Projectid").Message("项目id不为空")
	var validMsg []string
	for _, err := range valid.Errors {
		validMsg = append(validMsg, err.Message)
		log.Println(err.Key, err.Message)
	}
	if !utils.IsEmpty(validMsg) {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": strings.Join(validMsg, ",")}
		u.ServeJSON()
		return
	}
	userid := u.BaseController.UserUserId
	//雪花算法ID生成
	id := utils.SnowFlakeId()
	needs := new(NeedsSwimlanes)
	utils.SimpleCopyProperties(needs, dto)
	needs.Id = id
	needs.Userid = userid
	err = AddNeedsSwimlanes(*needs)
	if err == nil {
		u.Data["json"] = map[string]interface{}{"code": 1, "message": "信息创建成功", "swimlane": needs}
	} else {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "信息创建失败:" + err.Error()}
	}
	u.ServeJSON()
}

type SwimlaneToPlanDto struct {
	Started int64
	Ended   int64
}

// 如果你的 struct 实现了接口 validation.ValidFormer
// 当 StructTag 中的测试都成功时，将会执行 Valid 函数进行自定义验证
func (u *SwimlaneToPlanDto) Valid(v *validation.Validation) {
	v.Required(u.Started, "Started").Message("计划开始时间不为空")
	v.Required(u.Ended, "Ended").Message("计划结束时间不为空")
}

// @Title 一键转计划
// @Description   一键转计划
// @Param	body		body 	projects.SwimlaneToPlanDto	true		"body for Swimlane content"
// @Success 200 {string} 一键转计划
// @Failure 403 body is empty
// @router /changed/:id/plan [put]
func (u *NeedsSwimlaneProjectController) SwimlaneToPlanDto() {
	id, err := u.GetInt64(":id")
	if err != nil || id < 0 {
		// handle error
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "未知泳道"}
		u.ServeJSON()
		return
	}
	var dto SwimlaneToPlanDto
	err = json.Unmarshal(u.Ctx.Input.RequestBody, &dto)
	if err != nil {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "解析json错误" + err.Error()}
		u.ServeJSON()
		return
	}
	// 开始校验输入值
	valid := validation.Validation{}
	b, err := valid.Valid(&dto)
	if err != nil {
		// handle error
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "严重异常" + err.Error()}
		u.ServeJSON()
		return
	}
	if !b {
		var validMsg []string
		// validation does not pass
		for _, err := range valid.Errors {
			validMsg = append(validMsg, err.Message)
			log.Println(err.Key, err.Message)
		}
		if !utils.IsEmpty(validMsg) {
			u.Data["json"] = map[string]interface{}{"code": 0, "message": strings.Join(validMsg, ",")}
			u.ServeJSON()
			return
		}
	}
	userid := u.BaseController.UserUserId
	err = SwimlaneChangePlan(userid, id, dto)
	if err == nil {
		u.Data["json"] = map[string]interface{}{"code": 1, "message": "转换计划成功,请设置对应信息"}
	} else {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "转换计划失败:" + err.Error()}
	}
	u.ServeJSON()
}
